package edu.xmut.kakamusic.activity.tiktok;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Objects;

import cn.jzvd.Jzvd;
import edu.xmut.kakamusic.R;
import edu.xmut.kakamusic.bean.vo.RecommendVideoVO;
import edu.xmut.kakamusic.databinding.ActivityTiktokBinding;
import edu.xmut.kakamusic.utils.ApiResponse;
import edu.xmut.kakamusic.utils.RequestUtils;
import edu.xmut.kakamusic.utils.SPUtils;
import edu.xmut.kakamusic.utils.ToastUtils;
import edu.xmut.kakamusic.utils.WindowUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TiktokActivity extends AppCompatActivity {

    private static final String TAG = TiktokActivity.class.getSimpleName();
    private edu.xmut.kakamusic.databinding.ActivityTiktokBinding binding;
    private int currentPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EdgeToEdge.enable(this);
        super.onCreate(savedInstanceState);
        // 设置状态栏的外观
        WindowUtils.setLightStatusBarAppearance(this, true);
        // 初始化布局
        binding = ActivityTiktokBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        // 绑定布局
        initView();
    }

    private void initView() {
        ViewPagerLayoutManager viewPagerLayoutManager = new ViewPagerLayoutManager(this, OrientationHelper.VERTICAL);
        TikTokRecyclerViewAdapter adapter = new TikTokRecyclerViewAdapter();
        binding.rvTiktok.setLayoutManager(viewPagerLayoutManager);
        binding.rvTiktok.setAdapter(adapter);

        SPUtils spUtils = new SPUtils(this);
        String token = spUtils.getString("token");
        RequestUtils.getInstance().getRecommendVideo(token, String.valueOf(System.currentTimeMillis()))
                .enqueue(new Callback<ApiResponse<List<RecommendVideoVO>>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<List<RecommendVideoVO>>> call, Response<ApiResponse<List<RecommendVideoVO>>> response) {
                        if (response.isSuccessful()) {
                            ApiResponse<List<RecommendVideoVO>> apiResponse = response.body();
                            if (Objects.nonNull(apiResponse) && Objects.equals(apiResponse.getCode(), 200)) {
                                List<RecommendVideoVO> data = apiResponse.getData();
                                Log.d(TAG, "onResponse: " + data);
                                adapter.setData(data);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<List<RecommendVideoVO>>> call, Throwable t) {
                        ToastUtils.show(getBaseContext(), "网络错误" + t.getMessage());
                    }
                });

        viewPagerLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                //自动播放第一条
                autoPlayVideo();
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                if (currentPosition == position) {
                    Jzvd.releaseAllVideos();
                }
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                if (currentPosition == position) {
                    return;
                }
                autoPlayVideo();
                currentPosition = position;
            }
        });

        binding.rvTiktok.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                Jzvd jzvd = view.findViewById(R.id.tiktok_video);
                if (jzvd != null && Jzvd.CURRENT_JZVD != null && jzvd.jzDataSource != null &&
                        jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                    if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                        Jzvd.releaseAllVideos();
                    }
                }
            }
        });
    }


    private void autoPlayVideo() {
        if (binding.rvTiktok.getChildAt(0) == null) {
            return;
        }
        JzvdStdTikTok player = binding.rvTiktok.getChildAt(0).findViewById(R.id.tiktok_video);
        if (player != null) {
            player.startVideoAfterPreloading();
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}